package com.nlx.notes.module.service.impl.login;

import cn.hutool.core.util.StrUtil;
import com.nlx.notes.module.bean.dto.accountbook.AccountBookSaveDTO;
import com.nlx.notes.module.bean.dto.querydb.UserQueryDbDTO;
import com.nlx.notes.module.core.consts.GlobalConst;
import com.nlx.notes.module.core.util.DataUtils;
import com.nlx.notes.module.entity.Users;
import com.nlx.notes.module.service.ICategoriesService;
import com.nlx.notes.module.service.IAccountBooksService;
import com.nlx.notes.module.service.user.IUsersService;
import com.nlx.notes.module.service.login.RegisterService;
import com.nlx.notes.support.util.UniqueCodeGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class RegisterServiceImpl implements RegisterService {

    final IUsersService usersService;
    final IAccountBooksService accountBooksService;
    final ICategoriesService categoriesService;



    @Override
    public Users registerUser(String phone) {
        log.info("user register, phone {}", phone);
        Users user = new Users();
        user.setUsername(phone);
        user.setUserPassword(null);
        user.setUserPhone(phone);
        user.setEmail(null);
        user.setCreatedAt(LocalDateTime.now());
        user.setDelFlag(GlobalConst.DEL_FLAG_NORMAL);
        usersService.save(user);
        UserQueryDbDTO userQueryDbDTO = new UserQueryDbDTO();
        userQueryDbDTO.setPhone(phone);
        user = usersService.findUserByCondition(userQueryDbDTO);
        // 为新用户创建默认账本
        accountBooksService.createDefaultAccountBook(user);
        return user;
    }

    @Override
    public Users registerGuest(String userCode) {
        log.info("guest register");
        Users user = new Users();
        user.setUsername(GlobalConst.GUEST_NAME);
        if(StrUtil.isEmpty(userCode)){
            userCode = DataUtils.genUserCode();
        }
        user.setUserCode(userCode);
        user.setUserType(GlobalConst.USER_TYPE_GUEST);
        user.setUserPassword(null);
        user.setUserPhone(null);
        user.setEmail(null);
        user.setCreatedAt(LocalDateTime.now());
        user.setDelFlag(GlobalConst.DEL_FLAG_NORMAL);
        usersService.save(user);
        user.setUsername(UniqueCodeGenerator.genCode());
        usersService.updateById(user);
        // 为新用户创建默认账本
        accountBooksService.createDefaultAccountBook(user);
        return user;
    }

}
